const User = require('../models/user');
const PkManageModule = require('../models/private_key_manage');
const AElfModule = require('../models/aelf')

exports.form = (req, res) => {
    res.render('register', {title: 'Register'});
}

exports.submit = (req, res) => {
    const aelf = new AElfModule();
    
    const data = req.body.user;
    const user = new User({
        acct: data.acct,
        pass: data.pass
    });

    const pk = new PkManageModule({
        acct : data.acct,
        priKey : data.priKey
    });

    User.get_user_by_acct(data.acct ,(result) => {
        if (result) {
            console.log('acct has been taken!');
            res.redirect('back');
        } else {
            PkManageModule.get_user_by_priKey(data.priKey, (ret) => {
                if(result){
                    console.log('wallet has been used');
                    res.redirect('back');
                }
            })

            aelf.check_chain_state((state)=>{
                if(state){
                    aelf.load_wallet(pk.priKey , (wallet) => {
                        if(typeof(wallet) !== 'undefined'){
                            aelf.load_contract(true , (param) =>{
                                console.log("contract prepared");
                                aelf.register(param);
                            });
                        }
                            
                    });
                    user.save(()=>{})
                    pk.save((_id) => {
                        req.session.uid = _id;
                        res.redirect('/login');
                    })
                }
            })
            
        }
    })
}